<?php
/*
 * Copyright 2009 Eat Local Food, LLC
 * Copyright (c) 2007 osCommerce (this file was written after
 * code review of osCommerce).
 *
 * This file is part of gwtCommerce.
 *
 * gwtCommerce is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * gwtCommerce is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with gwtCommerce.  If not, see <http://www.gnu.org/licenses/>.
 */
class SpecialsComponent
{
	function SpecialsComponent()
	{
	}

	function action(&$params, $action)
	{
		return $this->query($params);
	}

	function query(&$params) 
	{
		$handle = get_class($this);
		$language_id = (int)$params['languageId'];

		$sqlQuery = 'select count(specials_id) as cnt ' .
		'from ' . TABLE_SPECIALS . ' where status = \'1\' and ((now() < expires_date and expires_date > 0) or expires_date = 0)';		
		$dataReturned = mysql_query($sqlQuery) or die(mysql_error());
		while($row = mysql_fetch_array($dataReturned))
		{
			$cnt = (int)$row['cnt'];
		}

		$rand = mt_rand(0, $cnt-1);

		$cache_id = $language_id . '_' . $rand;
		$json = read_cache($cache_id, $handle);
		if ($json)
		{
			if ($json == 'null') return null;
			else return json_decode($json, true);
		}

		$subParams['handle'] = $handle;
		$subParams['languageId'] = $language_id;
		$subParams['offset'] = $rand;
		$subParams['max_rows'] = 1;
		$subParams['searchSpecials'] = true;
		
		require_once('includes/components/ProductsSearchSubComponent.php');
		$subComponent = new ProductsSearchSubComponent();
		$value = $subComponent->query($subParams);
				
		if ($value != null) $json = json_encode($value);
		write_cache($json, $cache_id, $handle);

		return $value;
	}
}
?>
